import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import zscore

# 生成示例时间序列数据
np.random.seed(0)
dates = pd.date_range(start='2023-01-01', periods=100)
data = np.random.randn(100).cumsum()

# 创建DataFrame
df = pd.DataFrame(data, index=dates, columns=['Value'])

# 计算z-score
df['zscore'] = zscore(df['Value'])

# 检测异常点（假设z-score大于3或小于-3为异常点）
df['Anomaly'] = df['zscore'].apply(lambda x: x if abs(x) > 0.98 else np.nan)

# 绘制时间序列图及异常点
plt.figure(figsize=(10, 6))
plt.plot(df.index, df['Value'], label='Original Data')
plt.scatter(df.index, df['Anomaly'], color='red', label='Anomalies', zorder=5)
plt.title('Time Series Data with Anomaly Detection')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.grid(True)
plt.show()
